package com.backend.utils;


import com.qiniu.util.StringUtils;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CommonStringUtils {
    /**
     * 将字符串转为double
     *
     * @param str
     * @return
     */
    public static Double safeDouble(String str) {
        if (StringUtils.isNullOrEmpty(str)) {
            return 0.00;
        }
        double res = 0.00;
        try {
            res = Double.valueOf(str);
        } catch (Exception e) {
        }
        return res;
    }

    /**
     * 字符串转为Integer
     *
     * @param str
     * @return
     */
    public static Integer safeInteger(String str) {
        if (StringUtils.isNullOrEmpty(str)) {
            return 0;
        }
        int res = 0;
        try {
            res = Integer.valueOf(str);
        } catch (Exception e) {
        }
        return res;
    }

    /**
     * 转为字符串
     *
     * @param obj
     * @return
     */
    public static String safeString(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    public static String encodeString(String str, String charset) {
        Charset charset1 = Charset.forName(charset);
        str = new String(str.getBytes(Charset.defaultCharset()), charset1);
        return str;
    }

    public static String join(List<Object> list, String str) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Object object : list) {
            stringBuilder.append(CommonStringUtils.safeString(object)+str);
        }
        int size = stringBuilder.length();
        return size > 0 ? stringBuilder.substring(0,size-1) : "";
    }

    public static String DateToStr(Date date){
        if(date == null){
            return "";
        }
        SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return f.format(date);
    }
}
